package com.jt.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jt.mapper.ItemDescMapper;
import com.jt.pojo.Item;
import com.jt.pojo.ItemDesc;
import com.jt.vo.EasyUITable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jt.mapper.ItemMapper;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;

@Service
public class ItemServiceImpl implements ItemService {
	
	@Autowired
	private ItemMapper itemMapper;
	@Autowired
	private ItemDescMapper itemDescMapper;

	@Override
	public EasyUITable itemByPage(Integer page, Integer rows) {
		//1.通过分页对象 将page rows 进行参数封装
		IPage iPage=new Page(page,rows);
		QueryWrapper<Item> QueryWrapper = new QueryWrapper<>();
		QueryWrapper.orderByDesc("updated");
		//通过iPage对象封装其他的分页数据
		//核心语句
		IPage iPage1 = itemMapper.selectPage(iPage,QueryWrapper);
		List<Item> records = iPage1.getRecords();
		long total = iPage.getTotal();				//获取当前页的记录
		return new EasyUITable(total,records);
	}

	@Transactional	//标记方法使用事务控制
	@Override
	public void saveItem(Item item, ItemDesc itemDesc) {
		item.setStatus(1);		//设定启动状态
		itemMapper.insert(item);

		itemDesc.setItemId(item.getId());
		itemDescMapper.insert(itemDesc);
	}

	@Transactional	//标记方法使用事务控制
	@Override
	public void updateItem(Item item, ItemDesc itemDesc) {
		itemMapper.updateById(item);
		itemDesc.setItemId(item.getId());
		itemDescMapper.updateById(itemDesc);
	}

	//MP方式
	@Transactional
	@Override
	public void deleteItems(Long... ids) {
		QueryWrapper<Item> QueryWrapper = new QueryWrapper<>();
		List<Long> idsList = Arrays.asList(ids);
		QueryWrapper.in("id",idsList);
		itemMapper.delete(QueryWrapper);
		itemDescMapper.deleteBatchIds(idsList);
	}

	@Transactional
	@Override
	public void updateStatus(Integer status, Long[] ids) {
		QueryWrapper<Item> queryWrapper = new QueryWrapper<>();
		List<Long> idList = Arrays.asList(ids);
		queryWrapper.in("id",idList);
		Item item = new Item();
		item.setStatus(status);
		itemMapper.update(item,queryWrapper);
	}

	@Override
	public ItemDesc findItemDescById(Long id) {
		ItemDesc itemDesc = itemDescMapper.selectById(id);
		return itemDesc;
	}


//	@Override
//	public EasyUITable itemByPage(Integer page, Integer rows) {
//		long total=itemMapper.selectCount(null);
//		Integer start=(page-1)*rows;
//		List<Item> all = itemMapper.itemByPage(start,rows);
//		return new EasyUITable(total,all);
//	}
}
